package com.bodystm.temperature.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.temperature.bed.Bed;
import com.bodystm.temperature.bed.BedService;
import com.bodystm.temperature.patient.Patient;
import com.bodystm.temperature.patient.PatientBedDao;
import com.bodystm.temperature.patient.PatientBedService;
import com.bodystm.temperature.patient.PatientBedUser;
import com.bodystm.temperature.patient.PatientService;
import com.bodystm.temperature.server.Temperature;
import com.bodystm.temperature.server.TemperatureService;
import com.bodystm.temperature.web.EasyUiMessage;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.common.system.user.UserService;
import com.mimosa.util.config.Page;

@Controller
@RequestMapping("/bed")
public class BedController {
	@Resource
	private BedService bedService;

	@Resource
	private PatientService patientService;

	@Resource 
	private UserService userService;
	
	@Resource
	private TemperatureService temperatureService;
	
	@Autowired
	private PatientBedService patientBedUserService;

	@Autowired
	private PatientBedDao patientBedUserDao;
	
	@RequestMapping("/degreelisten.action")
	public String degreelisten(){
		return "bed/degreelisten";
	}

	@RequestMapping("/index.action")
	public String index(Page<Bed> page, Model model) {
		page = this.bedService.findByPage(page);

		Patient patient = null;
		Temperature temperature = null;
		for (Bed bed : page.getResult()) {
			patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
			if (patient != null) {
				bed.setPatient(patient);
				// 鑾峰彇娓╁害淇℃伅
				if (patient.getEquipNo() != null) {
					temperature = this.temperatureService.findLatestByEquipNoAndMeasureTime(patient.getEquipNo(),
							patient.getStartTime());
					if (temperature != null) {
						bed.setTiwen(temperature);
					}
				}
			}
		}
		model.addAttribute("start", page.getFirst());
		model.addAttribute("page", page.getPageNo());
		model.addAttribute("rows", page.getPageSize());
		model.addAttribute("totalCount", page.getTotalCount());
		model.addAttribute("bedList", page.getResult());
		return "bed/index";
	}

	@RequestMapping("/edit.action")
	public String edit(String id, String type, Model model) {
		if (StringUtils.isNotBlank(id)) {
			Bed bed = this.bedService.getEntity(id);
			model.addAttribute("bed", bed.getPatient());
		}
		return "bed/" + type;
	}
	
	/*
	 * 获取所有部门
	 */
	@RequestMapping("/listDepartments.action")
	@ResponseBody
	public String listDepartments(){
		List<TUser> users=this.userService.getAll();
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(TUser user:users){
			if(user.getUserName().toLowerCase().equals("admin")){
				//users.remove(user);
				continue;
			}
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", user.getId());
			bedJSONObject.put("name", user.getRealName());
			jSONArray.add(bedJSONObject);
			
		}
		//String json = null;
		
//		ObjectMapper mapper = new ObjectMapper();
//		try {
//			json = mapper.writeValueAsString(listAll);
//		} catch (JsonProcessingException e) {
//
//			json = null;
//		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/getBedsByDepartmentId.action")
	@ResponseBody
	public String getBedsByDepartmentId(String departmentId){
		List<Bed> lstBeds=this.bedService.findList("from Bed t where t.user.id=? and status='empty' order by t.name ASC", departmentId);
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(Bed bed:lstBeds){
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", bed.getId());
			bedJSONObject.put("name", bed.getName());
			jSONArray.add(bedJSONObject);
		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/outBed.action")
	@ResponseBody
	public String outBed(String ids, Model model) {
		this.bedService.outBed(ids);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Bed bed) {
		this.bedService.saveEntity(bed);
		return Boolean.TRUE.toString().toLowerCase();
	}

//	@ResponseBody
//	@RequestMapping("/add.action")
//	public String add(String bedid) {
//		java.util.List<Bed> lstBed = this.bedService.findList("from Bed t where t.name=? order by t.name ASC", bedid);
//		if (lstBed.size() > 0)
//			return "{\"success\":false,\"bedid\":\"1010\"}";
//		Bed bed = new Bed();
//		bed.setName(bedid);
//		this.bedService.saveEntity(bed);
//		  "{\"success\":true,\"bedid\":\"" + bedid + "\"}";
//	}
	/*
	 * 娣诲姞搴婁綅 by rxz 20151124
	 */
	@ResponseBody
	@RequestMapping("/add.action")
	public String add(String bedid,HttpSession session) {
        java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=? and t.user.id=? order by t.name ASC", bedid,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(lstBed.size()>0) return "{\"success\":false,\"bedid\":\""+bedid+"\"}";
		Bed bed=new Bed();
		bed.setName(bedid);
		bed.setStatus("empty");
		bed.setUser((TUser)session.getAttribute(UserContext.USER_ATTR));
		this.bedService.saveEntity(bed);
		return "{\"success\":true,\"bedid\":\""+bedid+"\"}";
	}
	/*
	 * 璁＄畻鍓╀綑鐢甸噺 by rxz
	 */
	private long getTime(Date datestart){
		long n= Math.abs((datestart.getTime()-(new Date()).getTime())/3600000);
		if(n>48)return 0;
		return 48-n;
	}
	/*
	 * 鑾峰彇鎵�湁搴婁綅鐨勫垪琛�
	 */
	@ResponseBody
	@RequestMapping("/listAll.action")
	public String listAll(HttpSession session) {
        java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? order by t.name ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(lstBed.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";
		JSONArray jSONArray = new JSONArray();
		JSONObject bedJSONObject = null;
		JSONObject personJSONObject = new JSONObject();
		JSONObject personTempJSONObject = null;
		Patient patient=null;
		Temperature temperature=null;
		float[] strTemp4degrees=null; float[] strTemp4degree=null;DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
		List<Temperature> temperatures;
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
		
		PatientBedUser patientBedUser=null;
		Temperature temperatureLatest=null;//获取剩余电量时使用
		for (Bed bed : lstBed) {
			bedJSONObject=new JSONObject();
			patient = this.patientService.findByBedIdAndEndTimeIsNull(bed
					.getId());
			if (patient != null) {
				bed.setPatient(patient);
				bed.setStatus("notempty");
				// 鑾峰彇娓╁害淇℃伅
				if (patient.getEquipNo() != null) {
					temperature = this.temperatureService
							.findLatestByEquipNoAndMeasureTime(
									patient.getEquipNo(),
									patient.getStartTime());
					if (temperature != null) {
						bed.setTiwen(temperature);
						bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
					}
				}
				
				bedJSONObject.put("listenstate", "listening");
				if(bed.getTiwen()!=null){
					//bedJSONObject.put("degree",bed.getTiwen().getMeasureNumOne());
					bedJSONObject.put("degree",decimalFormat.format(bed.getTiwen().getMeasureNumOne()));//保留两位小数
					//getTime(patient.getListenStartTime())
					if(bed.getTiwen().getMeasureNumOne()> patient.getRangeEnd()){
						bedJSONObject.put("state", "high");
					}
					else if(bed.getTiwen().getMeasureNumOne()<patient.getRangeStart()){
						bedJSONObject.put("state", "low");
					}
					else{
						bedJSONObject.put("state", "normal");
					}
				}
				
				
				bedJSONObject.put("range", patient.getRangeStart()+"~"+patient.getRangeEnd());
				if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null)
				bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime())+"~"+sdf.format(patient.getListenEndTime()));
				else if(patient.getListenStartTime()!=null)bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime()));
				bedJSONObject.put("num", patient.getEquipNo());
				if(patient.getListenStartTime()!=null)
				bedJSONObject.put("surplustime", getTime(patient.getListenStartTime()));
				//获取温度贴片的剩余电量
				temperatureLatest=temperatureService.getLatestTemprature(patient.getEquipNo());
				if(temperatureLatest!=null){
					bedJSONObject.put("powerNum", temperatureLatest.getPowerNum());
				}else{
					bedJSONObject.put("powerNum", 100);
				}
				bedJSONObject.put("personinfo", patient.getName()+"-"+patient.getSex()+"-"+patient.getAge()+"岁");
				bedJSONObject.put("name", patient.getName());
				bedJSONObject.put("sex", patient.getSex());
				bedJSONObject.put("age", patient.getAge());
				bedJSONObject.put("diagnosis",patient.getDisease());
				if(patient.getStartTime()!=null)
				bedJSONObject.put("roomtime", sdfDate.format(patient.getStartTime()));
				bedJSONObject.put("sicknum", patient.getMedicalRecordNumber());
				bedJSONObject.put("doctor", patient.getDoctor());
				bedJSONObject.put("patientid", patient.getId());//鑾峰彇鐥呬汉id浠ヤ究鍑洪櫌绛夊悗缁搷浣�
				
				
				personTempJSONObject=new JSONObject();
				personTempJSONObject.put("personid", patient.getPersonnelId());
				personTempJSONObject.put("type", patient.getMedicalTreatmentType());
				personTempJSONObject.put("address", patient.getAddress());
				
				//获取贴片工作状态
				patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
				if(patientBedUser!=null&&patientBedUser.getStatusOfDevice()!=null){
					bedJSONObject.put("deviceStatus", patientBedUser.getStatusOfDevice());
				}else{
					bedJSONObject.put("deviceStatus", 1);
				}
				
				try {
					temperatures=this.temperatureService
					.find24ByEquipNoAndMeasureTime(
							patient.getEquipNo(),
							patient.getStartTime());
					if(temperatures!=null&&temperatures.size()>0){
						Calendar date=Calendar.getInstance();
						date.setTime(temperatures.get(0).getMeasureTime());
						strTemp4degrees=new float[temperatures.size()];strTemp4degree=new float[temperatures.size()];
						if(temperatures.size()%2==0){
							strTemp4degree=new float[temperatures.size()/2];
						}
						else if(date.get(Calendar.HOUR_OF_DAY)%2==0){
							strTemp4degree=new float[(temperatures.size()+1)/2];
						}
						else{
							strTemp4degree=new float[temperatures.size()/2];
						}
						int countStr=0;
						
						for(int i=0;i<temperatures.size();i++){
							//temperatures.get(i).getMeasureTime().getHours()+
							date.setTime(temperatures.get(i).getMeasureTime());
							if(date.get(Calendar.HOUR_OF_DAY)%2!=0) continue;
							if(i==0||i==1){
								personTempJSONObject.put("times", date.get(Calendar.HOUR_OF_DAY));
							}
							strTemp4degrees[i]=temperatures.get(i).getMeasureNumOne();
							//personTempJSONObject.put("degrees", strTemp4degrees);
							//温度数据保留两位小数
							//strTemp4degree[i]=decimalFormat.format(temperatures.get(i).getMeasureNumOne());
							if(countStr<=strTemp4degree.length-1)
							strTemp4degree[countStr++]=temperatures.get(i).getMeasureNumOne();//decimalFormat.format(temperatures.get(i).getMeasureNumOne());
//							personTempJSONObject.put("degrees", strTemp4degree);
						}
						personTempJSONObject.put("degrees", strTemp4degree);

					}else{
						personTempJSONObject.put("times", null);
						personTempJSONObject.put("degrees", null);
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				personJSONObject.put(bed.getName(), personTempJSONObject);
			}
			else{
				bed.setStatus("empty");

			}
			bedJSONObject.put("bedid", bed.getName());
			bedJSONObject.put("idofbed", bed.getId());
			bedJSONObject.put("bedstate", bed.getStatus());
			jSONArray.add(bedJSONObject);

		}
		return "{\"total\":"+lstBed.size()+",\"data\":"+jSONArray.toString()+",\"otherdata\":"+personJSONObject.toString()+"}";
	}
	
	// @ResponseBody
	// @RequestMapping("/listAll.action")
	// public String listAll() {
	// java.util.List<Bed> lstBed=this.bedService.findList("from Bed t order by
	// t.name ASC");
	// if(lstBed.size()>0) return "{\"success\":false,\"bedid\":\"1010\"}";
	// Bed bed=new Bed();
	// bed.setName(bedid);
	// this.bedService.saveEntity(bed);
	// return "{\"success\":true,\"bedid\":\""+bedid+"\"}";
	// }

	@ResponseBody
	@RequestMapping(value = "/show.action", produces = { "application/json;charset=UTF-8" })
	public String show(String id) {
		Bed bed = this.bedService.getEntity(id);
		String data = "\"\"";
		if (bed != null && bed.getPatient() != null) {
			data = String.format("{\"equipNo\":\"%s\",\"name\":\"%s\",\"id\":\"%s\"}", bed.getPatient().getEquipNo(),
					bed.getPatient().getName(), bed.getPatient().getId());
		}
		EasyUiMessage message = new EasyUiMessage();
		message.setData(data);
		return message.toString();
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient, String startTimeStr, String endTimeStr) {
		if (StringUtils.isNotBlank(startTimeStr)) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				patient.setStartTime(format.parse(startTimeStr));
			} catch (ParseException e) {
				patient.setStartTime(new Date());
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.patientService.saveEntity(patient);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Bed bed) {
		this.bedService.deleteEntity(bed);
		return new EasyUiMessage().toString();
	}
	@ResponseBody
	@RequestMapping("/deleteByName.action")
	public String deleteByName(String bedid) {
		java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=?", bedid);
		if(lstBed.size()>0) {
			this.bedService.deleteEntity(lstBed.get(0));
		}
		return new EasyUiMessage().toString();
	}
}